<template>
  <div class="summary">
    <div class="top">
      <div class="left">
        <div class="left-top board-item">
          <div class="board-item-name">旋转扭矩</div>
          <div class="board-item-value">
            <span class="current-value" ref="rotateForce">{{
              timingData.torque
            }}</span>
            <span class="unit">KN·m</span>
          </div>
        </div>
        <div class="left-bottom board-item">
          <div class="board-item-name">给进/起拔压力</div>
          <div class="board-item-value">
            <span class="current-value">{{ timingData.pushPull }}</span>
            <span class="unit">KN</span>
          </div>
          <!-- <div class="chart"></div> -->
        </div>
      </div>
      <div class="middle">
        <EZUIKitJs />
      </div>
      <div class="right">
        <div class="right-top board-item">
          <div class="board-item-name">泥浆泵压力</div>
          <div class="board-item-value">
            <span class="current-value">{{ timingData.slurryPressure }}</span>
            <span class="unit">bar</span>
          </div>
          <!-- <div class="chart"></div> -->
        </div>

        <div class="right-bottom board-item">
          <div class="board-item-name">动力头转速</div>
          <div class="board-item-value">
            <span class="current-value">{{ timingData.rotationSpeed }}</span>
            <span class="unit">R/min</span>
          </div>
          <!-- <div class="chart"></div> -->
        </div>
      </div>
    </div>
    <div class="bottom">
      <div class="operator">
        <img class="avatar" src="../assets/image/logo.png" />
        <div class="detail">
          <div class="title">设备信息</div>
          <div class="operator-item">
            {{ "设备类型: " + deviceInfo.productName }}
          </div>
          <div class="operator-item">
            {{ "设备编码:" + deviceInfo.deviceCode }}
          </div>
          <div class="operator-item">
            {{ "设备工作状态: " + deviceInfo.accStatus }}
          </div>
        </div>
      </div>
      <div class="project-info">
        <div class="project-info-title">项目信息</div>
        <div class="list">
          <div class="project-info-item">
            <span>工程名称：</span>
            <span>{{ project.projectName }}</span>
          </div>
          <div class="project-info-item">
            <span>工程编码：</span>
            <span>{{ project.projectId }}</span>
          </div>
          <div class="project-info-item">
            <span>工程地点：</span>
            <span>{{ project.address }}</span>
          </div>
          <div class="project-info-item">
            <span>当前作业名称：</span>
            <span>{{ selectedSequence || '' }}</span>
          </div>
          <div class="project-info-item">
            <span>钻杆总数: </span>
            <span>{{ project.total || 500 }}</span>
          </div>
          <div class="project-info-item">
            <span>单根长度: </span>
            <span>{{ project.len || 9.7 + '(m)' }}</span>
          </div>
          <div class="project-info-item">
            <span>铺设管径: </span>
            <span>{{ project.outerRadius || 1500 + '(mm)' }}</span>
          </div>
          <div class="project-info-item">
            <span>工程地质信息: </span>
            <span>{{ project.geology || '暂无信息' }}</span>
          </div>
        </div>
      </div>
      <div class="btns" v-if="mode !== 'display'">
        <div class="btn">
          <el-button type="primary" :disabled="recording" @click="startRecord"
            >开始记录</el-button
          >
        </div>
        <div class="btn" @click="stopRecord">
          <el-button type="primary" plain :disabled="!recording"
            >结束记录</el-button
          >
        </div>
      </div>
    </div>
    <!-- 确认工作模式 -->
    <el-dialog
      :visible="showModeConfirm"
      center
      :modal="false"
      :show-close="false"
    >
      <div class="tip">请选择工作模式</div>
      <div class="mode-item">
        <span class="mode-name">演示模式: </span>
        <span class="desc"
          >此模式仅用作远程监控使用，所有数据均来自内部服务器，如果再远程办公室使用请选择此模式</span
        >
      </div>
      <div class="mode-item">
        <span class="mode-name">工作模式: </span>
        <span class="desc"
          >此模式下系统会主动采集，清理和上报数据。如有数据采集需求请选择用此模式</span
        >
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="plain" @click="selectMode('display')"
          >演示模式</el-button
        >
        <el-button type="primary" @click="selectMode('stretch')"
          >工作模式</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import getData from '@/utils/getData'
import { request } from '@/utils/request'
import { mapState } from 'vuex'
import EZUIKitJs from '../components/EZUIKitJs.vue'

export default {
  name: 'Summary',
  data () {
    return {
      // recording: false,
      //   定时任务timer
      timer: null,
      project: {
        projectName: '暂无信息',
        projectId: '暂无信息',
        address: '暂无信息'
      },
      worker: {
        name: '暂无信息',
        gender: '暂无信息',
        workId: '暂无信息'
      },

      // 设备信息
      deviceInfo: {
        productName: '水平定向钻',
        deviceCode: '',
        accStatus: '开机'
      }

      // showModeConfirm: true,
      //   实时钻机数据
      // slurryPressure: 0,
      // pushPull: 0,
      // rotationSpeed: 0,
      // torque: 0,
      // engineSpeed: 0
    }
  },
  components: {
    EZUIKitJs
    // borderBox1
  },

  computed: {
    ...mapState([
      'mode',
      'operator',
      'selectedProjectId',
      'projectList',
      'selectedSequence',
      'timingData',
      'CLNumber',
      'recording'
    ]),
    showModeConfirm () {
      return !this.mode
    }
  },

  watch: {
    selectedProjectId (val) {
      this.project = this.projectList.find((item) => item.projectId === val)
    }
  },

  beforeDestroy () {
    this.clearTimer()
  },

  methods: {
    // 选择工作模式
    selectMode (mode) {
      if (!mode) {
        this.$message({
          type: 'warning',
          message: '请选择工作模式',
          showClose: true
        })
      }
      if (mode === 'display') {
        this.$message({
          type: 'success',
          message: '您已进入演示模式',
          showClose: true
        })
        // this.showModeConfirm = false
        // return
      }
      if (mode === 'stretch') {
        this.$message({
          type: 'success',
          message: '您已进入数据采集模式',
          showClose: true
        })
        // this.showModeConfirm = false
        // this.startRecord()
      }
      this.$store.dispatch('setWorkingMode', mode)
    },

    // 开始记录数据
    startRecord () {
      if (this.mode !== 'stretch' || this.recording) return
      const { selectedProjectId, selectedSequence, CLNumber } = this
      console.log(this.mode)
      if (!selectedProjectId || !selectedSequence || !CLNumber) {
        this.$message({
          type: 'warning',
          message: '请确认是否已经选择工程信息,作业信息,当前钻杆数',
          showClose: true
        })
      } else {
        // this.recording = true
        this.$store.dispatch('getRecordState', true)
        // this.getTimingData()
        // this.startCron()
        // this.$message({
        //   type: 'success',
        //   message: '已经开始记录设备工作参数'
        // })
      }
    },

    // 上报数据-本地实时展示
    getTimingData () {
      getData().then((res) => {
        if (res.code === '103' || !res.data) {
          this.$message({
            type: 'warning',
            message: '数据请求异常，请联系徐工恢复数据接口！',
            showClose: true
          })
        } else {
          const {
            slurryPressure, // 泥浆压力
            pushPull, // 动力头推拉力
            rotationSpeed, // 动力头旋转速度,
            torque, // 动力头扭矩
            // currWorkTime, // 当前工作时间
            productName,
            vehId,
            accStatus,
            engineSpeed
          } = res.data[0]
          // 获取实时数据进行显示
          this.slurryPressure = slurryPressure
          this.pushPull = pushPull
          this.rotationSpeed = rotationSpeed
          this.torque = torque
          this.engineSpeed = engineSpeed
          this.deviceInfo.accStatus = accStatus
          this.deviceInfo.vehId = vehId
          this.deviceInfo.productName = productName
          // 上传数据
          this.uploadDataToServer(res.data[0])
        }
      })
    },

    // 向服务器上报数据
    uploadDataToServer (data) {
      const {
        currWorkTime, // 当前工作时间,
        vehId, // 车辆id
        slurryPressure, // 泥浆压力
        pushPull, // 推拉压力
        rotationSpeed, // 旋转速度
        torque, // 扭矩
        engineSpeed // 发动机转速
      } = data

      // 检查当前工程信息
      const { selectedProjectId, selectedSequence } = this
      if (!selectedProjectId || !selectedSequence) {
        this.$message({
          type: 'warning',
          message: '请检查工程信息和作业信息是否选择完整',
          showClose: true
        })
        return
      }

      const uploadData = {
        projectId: selectedProjectId,
        workName: selectedSequence,
        vehId,
        date: new Date(currWorkTime).getTime(),
        engineSpeed,
        runningForce: pushPull,
        rotateForce: torque,
        landForce: slurryPressure,
        rotateSpeed: rotationSpeed
      }
      this.$store.dispatch('uploadData', uploadData).then((res) => {
        console.log(res, 'uplaod')
      })
    },

    // 定时任务
    startCron () {
      this.clearTimer()
      this.getTimingData()
      this.timer = setInterval(() => {
        this.getTimingData()
        // this.getDesktop()
      }, 120000)
    },

    // 清楚定时任务
    clearTimer () {
      this.timer && clearInterval(this.timer)
    },

    stopRecord () {
      // this.recording = false
      this.$store.dispatch('getRecordState', false)
      // this.clearTimer()
      // if (!this.recording) return
      // this.recording = false
      // this.$message({
      //   type: 'info',
      //   message: '已结束数据记录'
      // })
    },

    // 读取桌面信息
    getDesktop () {
      const self = this
      const { desktopCapturer } = this.$electron

      desktopCapturer
        .getSource({ types: ['window', 'screen'] })
        .then(async (sources) => {
          for (const source of sources) {
            if (source.name.search('vue')) {
              try {
                const stream = await navigator.mediaDevices.getUserMedia({
                  audio: false,
                  video: {
                    mandatory: {
                      chromeMediaSource: 'desktop',
                      chromeMediaSourceId: source.id,
                      minWidth: 1280,
                      maxWidth: 1280,
                      minHeight: 720,
                      maxHeight: 720
                    }
                  }
                })
                self.handleStream(stream)
              } catch (error) {
                console.log(error, '-----')
              }
            }
          }
        })
    },

    // 处理视频流信息
    handleStream (stream) {
      const self = this
      const { innerWidth, innerHeight } = window
      const video = document.createElement('video')
      video.setAttribute(
        'style',
        `width:${innerWidth}px;height:${innerHeight}px`
      )
      video.srcObject = stream

      video.onloadedmetadata = () => {
        const captureImage = function () {
          const canvas = document.createElement('canvas')
          canvas.width = innerWidth
          canvas.height = innerHeight

          canvas
            .getContext('2d')
            .drawImage(video, 0, 0, innerWidth, innerHeight)

          const data = canvas.toDataURL().replace('data:image/png;base64,', '')
          self.getTableText(data)
        }
        captureImage()
      }
    },

    async getTableText (imageData) {
      // 获取access_token
      const url =
        'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=0zGTax5rOQxO955ty3v1D4hr&client_secret=uDIr6vxpDvhIfsbNhQQfqoCgbW8t8WW1'
      request({
        url,
        method: 'POST'
      })
        .then((res) => {
          console.log(res)
        })
        .catch((err) => console.log(err))

      // request({
      //   url,
      //   method: 'POST'
      // }, async function (err, res, body) {
      //   if (err) {
      //     console.log(err, 'err')
      //   }

      //   if (res) {
      //     console.log(res, 'res+++++')
      //   }

      //   console.log(body)

      //   // eslint-disable-next-line camelcase
      //   const { access_token } = JSON.parse(body)
      //   const bodyParams = `image=${encodeURIComponent(imageData)}`
      //   // eslint-disable-next-line camelcase
      //   const url = `https://aip.baidubce.com/rest/2.0/ocr/v1/form?access_token=${access_token}`
      //   request({
      //     url,
      //     method: 'POST',
      //     headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      //     body: bodyParams
      //   }, function (err, res, body) {
      //     if (err) {
      //       console.log(err, 'err')
      //       return
      //     }
      //     // const str = JSON.stringify(body, '', '\t')
      //     // const { forms_result }  = JSON.parse(body)
      //     // fs.writeFile('./excel.json', forms_result, function(err) {
      //     //     if(err) {
      //     //         console.log(err);
      //     //     }
      //     // })
      //     console.log(body, ';res, body')
      //     // const list = [];
      //     // const { forms_result } = JSON.parse(body);
      //     // const data = forms_result[0].body;
      //     // for (const item of data) {
      //     //   const { column, row, words } = item;
      //     //   if (!list[`${row}`]) {
      //     //     list[`${row}`] = [];
      //     //   }
      //     //   list[`${row}`][`${column}`] = words;
      //     // }
      //     // jsonFile.writeFile('./table2.json', body, function (err) {
      //     //   if (err) {
      //     //     console.log(err)
      //     //   }
      //     // })
      //   })
      // })
    }
  }
}
</script>

<style lang="scss" scoped>
.summary {
  padding: 0 0.625rem;
  height: 100%;
}
.date {
  line-height: 2.5rem;
  font-size: 2rem;
}

.tabs {
  display: flex;
  justify-content: flex-end;
}

.tab {
  margin-left: 1rem;
  padding: 0 1.25rem;
  min-width: 6.25rem;
  height: 2.5rem;
  line-height: 2.5rem;
  border-radius: 0.375rem;
  border: 1px solid #6eaeee;
}

.tab:hover {
  color: #f9f9f9;
  border: none;
  background-color: #409eff;
}

.active {
  color: #f9f9f9;
  border: none;
  background-color: #409eff;
}

.system-name {
  font-size: 2.25rem;
}

.top {
  margin-top: 0.9375rem;
  height: 60%;
  display: flex;
}

.left {
  flex: 1;
  margin-right: 1.25rem;
}

.board-item {
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  margin-bottom: 0.9375rem;
  padding: 1.25rem;
  min-width: 300px;
  height: 48%;
  border-radius: 0.375rem;
  box-shadow: 0.25rem 0.25rem rgba(0, 0, 0, 0.3);
  background-color: #fff;
  text-align: left;
}

.board-item-name {
  font-size: 1.5rem;
  line-height: 1.5rem;
  color: #333;
}

.board-item-value {
  flex: 1;
  display: flex;
  align-items: baseline;
  justify-content: center;
  margin-top: 1.875rem;
  line-height: 5rem;
  font-size: 2rem;
  vertical-align: baseline;
  text-align: center;
}

.unit {
  color: #333;
}

.current-value {
  margin-right: 0.3125rem;
  font-size: 5rem;
  color: #33fa01;
}

.middle {
  flex: 2;
  height: 98%;
  box-sizing: border-box;
  padding: 0.9375rem;
  // height: 26.25rem;
  margin-right: 1.25rem;
  background-color: burlywood;
  text-align: center;
}

.video-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 0.9375rem;
  height: 50%;
}

.video-item {
  position: relative;
  width: 48%;
  height: 90%;
  background-color: rgba(0, 0, 0, 0.3);
}

.video-title {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
  box-sizing: border-box;
  padding: 0.3125rem 0.9375rem;
  width: 100%;
  font-size: 1rem;
  text-align: left;
  background-color: rgba(0, 0, 0, 0.6);
}

.right {
  flex: 1;
}

.bottom {
  box-sizing: border-box;
  margin-top: 0.625rem;
  // height: 12.5rem;
  height: 35%;

  display: flex;
  justify-content: space-between;
}

.operator {
  display: flex;
  justify-content: flex-start;
  box-sizing: border-box;
  padding: 0.9375rem;
  width: 20.625rem;
  background-color: #fff;
}

.avatar {
  width: 6.25rem;
  height: auto;
  object-fit: cover;
}

.detail {
  margin-left: 1.25rem;
  text-align: left;
  color: #000;
}

.title {
  text-align: center;
  font-size: 1.5rem;
  line-height: 1.5rem;
  color: #409eff;
}

.operator-item {
  margin-top: 1rem;
  font-size: 1rem;
  line-height: 1.25rem;
}

.project-info {
  flex: 2.5;
  // display: flex;
  // justify-content: space-between;
  // flex-wrap: wrap;
  padding: 0.9375rem;
  background-color: white;
  border-left: 0.125rem solid #e2e2e2;
  text-align: left;
  color: #000;
  &-title {
    text-align: center;
    font-size: 1.5rem;
    line-height: 1.5rem;
    color: #409eff;
  }

  .list{
    display: flex;
    flex-wrap: wrap;
    overflow-y: auto;
  }
}

.project-info-item {
  border: 1px solid #409eff;
  margin-top: 0.9375rem;
  margin-right: 2.5rem;
  padding: .5rem;
  // line-height: 1.5rem;
  height: auto;
  width: 16rem;
}

input {
  display: inline-block;
  margin-right: 0.9375rem;
  padding: 0 0.625rem;
  width: 12.5rem;
  line-height: 1.75rem;
  outline: none;
  border: none;
  border: 1px solid #409eff;
  border-radius: 0.3125rem;
}

.btns {
  display: flex;
  align-items: center;
  flex-direction: column;
  width: 20.625rem;
  border-left: 1px solid #e2e2e2;
  background-color: #fff;
}

.btn {
  margin-top: 3.125rem;
  width: 9.375rem;
}

.project-btn {
  width: 11.25rem;
  text-align: center;
}

.submit-btn {
  margin: 0.9375rem auto;
  width: 18.75rem;
}
</style>

<style lang="scss">
.el-dialog {
  display: flex;
  flex-direction: column;
  align-items: center;
  .tip {
    font-size: 1.625rem;
    color: red;
    text-align: center;
  }

  .mode-item {
    display: flex;
    align-items: flex-start;
    margin-top: 1.25rem;
    font-size: 1.25rem;
    .mode-name {
      flex-shrink: 0;
      width: 6.25rem;
      font-weight: bold;
      color: #000;
    }
  }
}
</style>
